const fs = require("fs");
const path = require("path");
const { PDFDocument, PDFImage } = require("pdf-lib");

/**
 * Embed an image into a PDF document.
 *
 * @param {PDFDocument} pdfDoc PDF document to embed the image into.
 * @param {string} imagePath Path to the image file.
 *
 * @returns {PDFImage} The embedded image.
 */
async function embedImage(pdfDoc, imagePath) {
  const ext = path.extname(imagePath);
  const bytes = fs.readFileSync(imagePath);
  if (ext.toLowerCase() == ".jpg") {
    return await pdfDoc.embedJpg(bytes);
  }
  if (ext.toLowerCase() == ".png") {
    return await pdfDoc.embedPng(bytes);
  }
  return undefined;
}

async function imagesToPdf(imagePaths, outputPath = "output.pdf") {
  const pdfDoc = await PDFDocument.create();

  // const sortedPaths = imagePaths.sort();

  for (const imagePath of imagePaths) {
    console.log("processing", imagePath);
    const img = await embedImage(pdfDoc, imagePath);
    if (!img) {
      console.log("unsupported image format", imagePath);
      continue;
    }

    const page = pdfDoc.addPage([img.width, img.height]);
    page.drawImage(img, {
      x: 0,
      y: 0,
      width: img.width,
      height: img.height,
    });
  }

  console.log("writing pdf >>>", outputPath, "...");

  const pdfBytes = await pdfDoc.save();
  fs.writeFileSync(outputPath, pdfBytes);
}

module.exports = imagesToPdf;
